from db_tools.db_handler import DbHandler
from tools.save_image_to_device import *
from tools.common_tools import image_to_string

"""
日志分析模块,主要是用来和生产日志那里进行通信的模块,日志分析,还有日志目录查看.
"""



class LoggerTool(object):
    def __init__(self):
        self.logger = HdLogger()
        self.db = DbHandler()
        self.debugFileUsed = ""
        self.debugInfoList = []  # 日志显示总的记录内容,显示的时候,五十条五十条的显示,不要一下显示太多.
        self.debugInfoIdList = []  # 日志显示的所有的索引
        self.debugInfoShowTimes = 1  # 第几次显示日志.
        self.cutterImageWebShowIndex = 0  # 界面上显示的图像编号的索引值,用来下一张和上一张的时候,来切换不同的值
        self.showDataLimit = 50  # 界面上展示的数据条目
        self.showimageIndexList = [],
        self.showimageIndexList = []

    @staticmethod
    def get_all_debug_id(fileName):
        """
        根据debug文件的内容,获取所有的板子的编号
        :param fileName 要处理的debug的文件名
        :return:
        """
        totalIdList = []
        filePath = os.path.join(DEBUG_DIR, fileName)
        with open(filePath, encoding="utf-8") as f:
            while True:
                line = f.readline()
                if len(line) <= 0:
                    break
                if "id_" in line and " - " in line:
                    idFinded = line.split(" - ")[1].split(" ")[0][3:]
                    if idFinded not in totalIdList:
                        totalIdList.append(idFinded)
        return totalIdList

    @staticmethod
    def get_total_debug_file():
        """
        获取所有的日志文件名称
        :return:
        """
        debugFile = []
        for root, dirs, files in os.walk(DEBUG_DIR):
            for file in files:
                if root != DEBUG_DIR:
                    continue
                if file[-4:] == ".txt":
                    debugFile.append(file)
        return debugFile

    def get_debug_info_by_index(self, boardIndex):
        """
        根据板的编号获取日志信息
        :param boardIndex: 板编号
        :return:
        """
        debugInfoWeb = []
        debugFilePath = os.path.join(DEBUG_DIR, self.debugFileUsed)
        with open(debugFilePath, encoding='utf-8') as f:
            while True:
                line = f.readline()
                if len(line) <= 0:
                    break
                if boardIndex not in line:
                    continue
                timeInfoSplit = " - "
                if timeInfoSplit in line:
                    head = line.split(timeInfoSplit)[0]
                    content = line.split(timeInfoSplit)[1]
                else:
                    head = ""
                    content = line
                debugInfoWeb.append([head, content])

            return debugInfoWeb

    def get_debug_info_by_key_word(self, keyWord):
        debugInfoWeb = []
        debugFilePath = os.path.join(DEBUG_DIR, self.debugFileUsed)
        with open(debugFilePath, encoding='utf-8') as f:
            while True:
                line = f.readline()
                if len(line) <= 0:
                    break
                if keyWord not in line:
                    continue
                timeInfoSplit = " - "
                if timeInfoSplit in line:
                    head = line.split(timeInfoSplit)[0]
                    content = line.split(timeInfoSplit)[1]
                else:
                    head = ""
                    content = line
                debugInfoWeb.append([head, content])

            return debugInfoWeb

    def get_debug_info_by_hour_time(self, hourTime):
        """
        根据时间去获取日志,比较时间,如果大于这个时间,就从当前开始保存日志信息.
        :param hourTime: 时间的小时
        :return:
        """
        debugInfoWeb = []
        debugFilePath = os.path.join(DEBUG_DIR, self.debugFileUsed)
        timeIsRight = False
        with open(debugFilePath, encoding='utf-8') as f:
            while True:
                line = f.readline()
                if len(line) <= 0:
                    break
                if " - " not in line:
                    continue
                timeStr = line.split(" ")[1]
                hourFinded = int(timeStr[:2])
                minuteFinded = int(timeStr[3:5])
                secondFinded = int(timeStr[6:8])
                hour = int(hourTime[:2])
                minute = int(hourTime[3:5])
                second = int(hourTime[6:8])

                if not timeIsRight:
                    if hourFinded < hour:
                        continue
                    elif hourFinded == hour:
                        if minuteFinded < minute:
                            continue
                        elif minuteFinded == minute:
                            if secondFinded < second:
                                continue
                timeIsRight = True
                timeInfoSplit = " - "
                if timeInfoSplit in line:
                    head = line.split(timeInfoSplit)[0]
                    content = line.split(timeInfoSplit)[1]
                else:
                    head = ""
                    content = line
                debugInfoWeb.append([head, content])

            return debugInfoWeb

    @staticmethod
    def get_debug_info_by_name(debugFile):
        """
        根据文件名,获取日志文件.
        :param debugFile: 日志的文件名称.
        :return:
        """
        debugInfoWeb = []
        debugFilePath = os.path.join(DEBUG_DIR, debugFile)
        with open(debugFilePath, encoding="utf-8") as f:
            while True:
                line = f.readline()
                if len(line) <= 0:
                    break
                timeInfoSplit = " - "
                if timeInfoSplit in line:
                    head = line.split(timeInfoSplit)[0]
                    content = line.split(timeInfoSplit)[1]
                else:
                    head = ""
                    content = line
                debugInfoWeb.append([head, content])

            return debugInfoWeb

    def web_request_get_logger_info(self, fileName):
        """
        前端界面请求了日志文件和内容
        :param fileName: 要显示的日志文件名称,如果是空,就默认显示第一条日志.
        :return:
        """
        # 获取所有的日志文件,并且按照日期进行排序.
        totalFiles = self.get_total_debug_file()
        totalFilesSortedByDate = sorted(totalFiles, reverse=True)
        if fileName == "":
            self.debugFileUsed = totalFilesSortedByDate[0]
        else:
            self.debugFileUsed = fileName

        debugInfo = self.get_debug_info_by_name(self.debugFileUsed)
        # 只选取最后面的100条数据进行展示,并且是倒叙的方式
        debugInfo = debugInfo[::-1]
        self.debugInfoList = debugInfo
        debugInfoEndFlag = True
        if len(debugInfo) > 100:
            debugInfo = debugInfo[:100]
            debugInfoEndFlag = False
        self.debugInfoList = self.debugInfoList[100:]  # 100往后面的个数,将前面100条数据搞掉
        boardIndexList = self.get_all_debug_id(self.debugFileUsed)
        self.debugInfoIdList = boardIndexList
        if len(boardIndexList) >= self.showDataLimit:
            boardIndexList = boardIndexList[:self.showDataLimit]
        return totalFilesSortedByDate, debugInfo, boardIndexList, debugInfoEndFlag

    def web_request_get_logger_info_by_board_index(self, boardIndex):
        """
        根据图像名称和物料的id来获取要显示的日志
        :param boardIndex 作业板的编号
        :return:
        """
        debugEndFlag = True
        id_boardIndex = "id_{}".format(boardIndex)
        debugInfo = self.get_debug_info_by_index(id_boardIndex)
        if len(debugInfo) == 0:
            debugInfo = [["日志id_{} ".format(boardIndex), "的日志记录不存在!"]]
        return debugInfo, debugEndFlag

    def web_request_get_logger_info_by_key_word(self, keyword):
        """
        根据关键字来获取要显示的日志
        :param keyword  关键字
        :return:
        """
        debugEndFlag = True
        debugInfo = self.get_debug_info_by_key_word(keyword)
        if len(debugInfo) == 0:
            debugInfo = [["关键字: {} ".format(keyword), "的日志记录不存在!"]]
        self.debugInfoList = debugInfo
        if len(debugInfo) >= 100:
            self.debugInfoList = debugInfo[100:]
            debugInfo = debugInfo[:100]
            debugEndFlag = False
        return debugInfo, debugEndFlag

    def web_request_get_logger_info_by_hour_time(self, timeHour):
        """
        前端界面上点击了按照时间去获取日志
        :param timeHour: 界面上选取的时间
        :return:
        """
        if timeHour == "":
            debugInfo = [["时间段_{}".format(timeHour), "不能为空"]]
        else:
            debugInfo = self.get_debug_info_by_hour_time(timeHour)
        if len(debugInfo) == 0:
            debugInfo = [["时间段_{}".format(timeHour), "的日志记录不存在"]]
        self.debugInfoList = debugInfo
        debugEndFlag = True
        if len(debugInfo) >= 100:
            self.debugInfoList = debugInfo[100:]
            debugInfo = debugInfo[:100]
            debugEndFlag = False
        return debugInfo, debugEndFlag


    def web_request_get_produce_amount_record(self):
        """
        前端界面获取月产量的请求
        :return:
        """
        res, data = self.db.get_produce_record_table_data()
        if res != "ok":
            return []
        recordList = [data.get(str(i)) for i in range(1, 13)]
        webShowDataList = [(str((index + 1)) + "月", data) for index, data in enumerate(recordList)]

        dayAmountDict = data.get("dayAmount")
        newDayAmountTableVal = []
        tableDataIndex1 = "dayIndex"
        tableDataIndex2 = "dayAmount"
        dayAmountDictKey = dayAmountDict.keys()
        newAmountDictKey = sorted(dayAmountDictKey, reverse=True)
        nowDay = get_time_now_string()[5:10]
        if len(newAmountDictKey) > 31:  # 如果超过了31天
            nowDayIndex = newAmountDictKey.index(nowDay)
            newAmountDictKey = newAmountDictKey[nowDayIndex:]
        if len(newAmountDictKey) >= 31:
            newAmountDictKey = newAmountDictKey[:32]

        newAmountDict = {key: dayAmountDict[key] for key in newAmountDictKey}

        for key, val in newAmountDict.items():
            newVal = {
                "key": key,
                tableDataIndex1: key,
                tableDataIndex2: val
            }
            newDayAmountTableVal.append(newVal)

        return webShowDataList, newDayAmountTableVal




if __name__ == '__main__':
    hdlt = LoggerTool()
    hdlt.web_request_get_logger_info("")
    idList = hdlt.get_all_debug_id("2021-11-23_debug.txt")
    print(idList)
    # hdlt.web_request_get_line_image_dir_board_list("识别失败")